package com.backedserver.controller.system;

import com.common.base.BindUpdateBy;
import com.common.base.DictionaryAware;
import com.common.constants.Constants;
import com.common.entity.system.DictionaryEntity;
import com.common.entity.system.DictionaryTypeEntity;
import com.common.properties.JwtProperties;
import com.common.requestvo.standvalue.StandValueReqVo;
import com.common.requestvo.system.DictionaryReqVo;
import com.common.requestvo.system.DictionaryTypeReq;
import com.common.service.system.DictionaryService;
import com.common.service.system.DictionaryTypeService;
import com.common.utils.JwtTokenUtils;
import com.common.utils.PageUtil;
import com.common.utils.ResultVoUtil;
import com.common.utils.TokenUtils;
import com.common.vo.PageVo;
import com.common.vo.ResultVo;
import com.common.vo.standvalue.StandValueVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典处理Controller处理层
 *
 * @author johnny
 */
@Api(tags = "字典模块")
@Slf4j
@RestController
@RequestMapping("/dictionary")
public class DictionaryController {
    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private DictionaryTypeService dictionaryTypeService;

    @Autowired(required = false)
    private HttpServletRequest request;

    public static Map<String, String> dictionaryMap = new HashMap<>();

    @PostConstruct
    public void init() {
        //查询 语言字典， 节目 一级 二级分类 字典
//        String[] typeArr = {DictionaryTypeEnum.LANGUAGE_ID.getCode(), DictionaryTypeEnum.PROGRAM_TYPE.getCode(), DictionaryTypeEnum.PROGRAM_CLASS.getCode(), DictionaryTypeEnum.TAG.getCode()};
//        List<DictionaryEntity> dictionaryEntities = dictionaryService.findByType(typeArr);
//        dictionaryEntities.stream().forEach(dictionaryEntity -> {
//            dictionaryMap.put(dictionaryEntity.getName(), dictionaryEntity.getValue());
//        });
    }

    private Specification<DictionaryEntity> whereSpec(final DictionaryReqVo entity) {
        return (root, query, cb) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if (StringUtils.isNotEmpty(entity.getName())) {
                predicates.add(cb.like(root.get("name"), "%" + entity.getName() + "%"));
            }
            if (StringUtils.isNotEmpty(entity.getValue())) {
                predicates.add(cb.equal(root.get("value"), entity.getValue()));
            }
            if (StringUtils.isNotEmpty(entity.getType())) {
                predicates.add(cb.equal(root.get("type"), entity.getType()));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
    }

    @ApiOperation(value = "根据条件查询字典列表(不分页)", notes = "根据条件查询字典列表(不分页)")
    @GetMapping
    public ResultVo searchTypeAll(@ModelAttribute DictionaryReqVo entity) throws JsonProcessingException {

        List<DictionaryEntity> data = dictionaryService.findAll(whereSpec(entity));
        Map<String, List<DictionaryEntity>> maps = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(data)) {
            data.forEach(item -> {
                if (maps.get(item.getType()) == null) {
                    maps.put(item.getType(), Lists.newArrayList(item));
                } else {
                    maps.get(item.getType()).add(item);
                }
            });
        }
        return ResultVoUtil.success(maps);
    }


    @GetMapping("/listByCondition")
    @ApiOperation(value = "根据条件查询字典信息 (分页)")
    public ResultVo listByCondition(DictionaryReqVo dictionaryReqVo,
                                    PageVo pageVo) {
        pageVo.setPageNumber(pageVo.getPageNumber() - 1);
        Page<DictionaryEntity> page = dictionaryService.listByCondition(dictionaryReqVo, PageUtil.initPage(pageVo));
        return ResultVoUtil.success(page);
    }

    @ApiOperation(value = "获取字典项类型列表", notes = "获取字典项类型列表")
    @GetMapping("/types")
    public ResultVo findAllTypes() {
        List<DictionaryTypeEntity> dictionaryTypeEntityList = dictionaryTypeService.getAll();
        return ResultVoUtil.success(dictionaryTypeEntityList);
    }

    @ApiOperation(value = "删除类型", notes = "删除类型")
    @PostMapping("/deleteType")
    public ResultVo findAllTypes(Long id) {
        try {
            dictionaryTypeService.delete(id);
        } catch (Exception e) {
            log.error("删除失败", e);
            return ResultVoUtil.error(500, "删除失败");
        }
        return ResultVoUtil.success("删除成功");
    }

    @ApiOperation(value = "新增字典项类型")
    @PostMapping("addType")
    public ResultVo add(@RequestBody DictionaryTypeEntity dictionaryTypeEntity) {
        dictionaryTypeEntity.setId(null);
        dictionaryTypeEntity.setCreateBy(JwtTokenUtils.getRealNameFromReq(request));
        DictionaryTypeEntity typeEntity = this.dictionaryTypeService.save(dictionaryTypeEntity);
        if (null != typeEntity) {
            return ResultVoUtil.success("添加成功");
        }
        DictionaryAware.refresh(dictionaryService);
        return ResultVoUtil.error("添加失败");
    }


    @ApiOperation(value = "字典新增")
    @PostMapping("/add")
    public ResultVo add(@RequestBody DictionaryEntity dictionaryEntity) {
        dictionaryEntity.setId(null);
        dictionaryEntity.setCreateBy(JwtTokenUtils.getRealNameFromReq(request));
        dictionaryService.saveDic(dictionaryEntity);

        DictionaryAware.refresh(dictionaryService);
        return ResultVo.success("添加成功");
    }

    @ApiOperation(value = "字典修改")
    @PostMapping("/edit")
    public ResultVo edit(@RequestBody DictionaryEntity dictionaryEntity) {
        dictionaryEntity.setUpdateBy(JwtTokenUtils.getRealNameFromReq(request));
        dictionaryService.editDic(dictionaryEntity);
        return ResultVo.success("编辑成功");
    }


    /**
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @ApiOperation(value = "删除字典信息")
    @ApiImplicitParam(name = "id", value = "字典id", dataType = "Long", example = "1")
    public ResultVo delete(@PathVariable Long id) {
        dictionaryService.delete(id);
        return ResultVoUtil.success();
    }

    @PostMapping("/findByTypeList")
    @ApiOperation(value = "根据类型 查询字典信息")
    public ResultVo findByTypeList(@RequestBody DictionaryTypeReq dictionaryTypeReq) {
        List<DictionaryEntity> dictionaryEntities = dictionaryService.findByTypeList(dictionaryTypeReq);

        Map<String, List<DictionaryEntity>> collect = dictionaryEntities.stream()
                .collect(Collectors.groupingBy(DictionaryEntity::getType,
                        Collectors.mapping(v -> v, Collectors.toList())));
        return ResultVoUtil.success(collect);
    }

}
